<?php

declare(strict_types=1);

namespace app\shop\controller\admin\decorate;

use think\Request;
use think\Response;
use think\facade\Db;
use sheep\controller\Backend;
use sheep\exception\SheepException;
use app\shop\model\decorate\Page as PageModel;

class Page extends Backend
{

    protected $model = null;

    public function initialize()
    {
        $this->model = new PageModel();
    }
    /**
     * 页面列表
     *
     * @return Response
     */
    public function list(): Response
    {
        $group = $this->request->param('group', 'keywords');
        $data = $this->model->sheepFilter()->where('group', $group)->select(); 
        return success('操作成功', $data);
    }

    /**
     * 页面详情
     *
     * @param  int $id
     * @return \think\Response
     */
    public function detail($id)
    {
        $type = $this->request->param('type');
        $page = $this->model->where(['decorate_id' => $id, 'type' => $type])->find();
        return success('获取成功', $page);
    }

    /**
     * 编辑
     *
     * @param  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        $type = $this->request->param('type');
        $page = $this->request->param('page');
        $image = $this->request->param('image');

        $pageRow = PageModel::where(['decorate_id' => $id, 'type' => $type])->find();

        if($pageRow) {
            $pageRow->page = $page;
            $pageRow->image = $image;
            $pageRow->save();
        }else {
            PageModel::create([
                'decorate_id' => $id,
                'type' => $type,
                'page' => $page,
                'image' => $image
            ]);
        }
        return success('保存成功');

    }

    /**
     * 删除
     *
     * @param  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $is_real = $this->request->param('is_real', 0);
        Db::transaction(function () use ($id, $is_real) {
            $reply = $this->model->findOrFail($id);
            if ($is_real) {
                $reply->force()->delete();
            } else {
                $reply->delete();
            }
        });

        return success('删除成功');
    }

}
